/** 颜色输入框 */

import { Popover } from 'antd';
import React from 'react';
import { ColorResult, SketchPicker } from 'react-color';
import styles from './index.module.less';

export interface IColorInputProps {
    value?: number;
    onChange?: (e: number) => void;
    style?: React.CSSProperties;
}

export default function ColorInput(props: IColorInputProps) {

    const [value, setValue] = React.useState(props.value ? `#${props.value.toString(16)}` : '#000000');

    const onChangeSketchPicker = React.useCallback((e: ColorResult) => {
        setValue(e.hex);
        props.onChange && props.onChange(parseInt(e.hex.replace('#', '0x')))
    }, [props])

    const content = React.useMemo(() => {
        return (
            <SketchPicker disableAlpha className={styles.sketchPicker} color={value} onChange={onChangeSketchPicker} />
        )
    }, [onChangeSketchPicker, value])

    React.useEffect(() => {
        setValue(props.value ? `#${props.value.toString(16)}` : '#000000')
    }, [props.value])

    return (
        <div className={styles.colorInput} style={props.style} >
            <Popover content={content} trigger="click">
                <i style={{ background: `${value}` }} ></i>
            </Popover>
            <span>{value}</span>
        </div>
    )
}